import React, {useState, forwardRef, useImperativeHandle} from 'react';
import {message, Modal} from "antd";
import TextArea from "antd/es/input/TextArea";
import {store} from "../../store/store";

function LeaveMessage(props, ref) {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [TextAreaText, setTextAreaText] = useState('');
    const showModal = (name) => {
        // 验证tokek
        if (store.getState().UserRedux.token) {
            if (name) {
                setTextAreaText(`@${name}:`)
            }
            setIsModalOpen(true);
        } else {
            message.warning('请先登录')
        }

    };
    const handleOk = () => {
        props.submitMessage(TextAreaText);
        setIsModalOpen(false);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const afterOpenChange = (index) => {
        if (!index) {
            setTextAreaText('')
        }
    }

    const TextAreaChange = (e) => {
        setTextAreaText(e.target.value)
    }

    useImperativeHandle(ref, () => {
        return {
            showModal
        }
    })

    return (
        <>
            <Modal title="留言发表~~" afterOpenChange={afterOpenChange} open={isModalOpen} onOk={handleOk}
                   onCancel={handleCancel}>
                <TextArea rows={4} value={TextAreaText} onChange={TextAreaChange} placeholder="请输入100字以内的留言"
                          maxLength={100}/>
            </Modal>
        </>
    );
}

export default forwardRef(LeaveMessage);
